package com.lagou.rpc.provider.server;

import org.I0Itec.zkclient.ZkClient;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class ZkServer implements DisposableBean {

    private ZkClient zkClient;

    private String rootNote = "/rpcServer";

    private String path;

    private String data;

    private String nettyIp;

    private Integer nettyPort;

    public void setZkServer(ZkClient zkClient,String nettyIp, Integer nettyPort) {
        this.zkClient = zkClient;
        this.nettyIp = nettyIp;
        this.nettyPort = nettyPort;
    }

    public String zkUp(){
        if (!zkClient.exists(rootNote)){
            zkClient.createPersistent(rootNote);
        }
        path = rootNote + "/" + nettyIp;
        data = nettyIp + ":" + nettyPort;
        zkClient.createEphemeral(path,data);
        //如果服务器上线时在Zookeeper注册成功，则读取服务器注册信息并返回
        if (getZkChildren()){
            Object o = zkClient.readData(path);
            return "本服务器上线注册zookeeper成功！" + "。注册名：" + nettyIp + "注册内容：" + o;
        }
        return "本服务器上线注册zookeeper失败！";
    }

    //判断服务器上线是否建立临时节点成功
    private Boolean getZkChildren(){
        List<String> childrenNotes = zkClient.getChildren(rootNote);
        for (String childrenNote : childrenNotes) {
            System.out.println(childrenNote);
            if (nettyIp.equals(childrenNote)){
                return true;
            }
        }
        return false;
    }

    @Override
    public void destroy() throws Exception {
        if (path != null) {
            zkClient.deleteRecursive(path);
        }
    }
}
